<?php
namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Product as ProductModel;
use think\Log;


class Product extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function list()
    {
        if ($this->request->isOptions()) {
            exit();
        }

        $page = $this->request->get('page', 0);
        $category = $this->request->get('category', 0);
        $page_size = $this->request->get('pageSize', config('api.page_size'));

        $query = ProductModel::where('status', 1);
        if (!empty($category)) {
            $query = $query->where("FIND_IN_SET('$category', `category_ids`)");
        }
        $count = $query->count();

        $query = ProductModel::where('status', 1);
        if (!empty($category)) {
            $query = $query->where("FIND_IN_SET('$category', `category_ids`)");
        }
        $list = $query->order('weigh desc,createtime desc')
//            ->field('id,title,slug,desc,content,cover_image,image_list,updatetime')
            ->limit($page * $page_size, $page_size)
            ->select();

        $ret = [
            'entries' => collection($list)->toArray(),
            'count' => $count,
            'page' => $page,
            'page_size' => $page_size,
            'domain' => $this->request->domain(),
        ];
        $this->success('返回成功', $ret);
    }

    public function detail()
    {
        if ($this->request->isOptions()) {
            exit();
        }

        $product_id = $this->request->get('productId');
        $product = ProductModel::where('id', $product_id)
            ->where('status', 1)
            ->find();
        if (empty($product)) {
            $this->error('未找到对应商品', null, 404);
        }
        $ret = [
            'entry' => $product,
            'domain' => $this->request->domain(),
        ];
        $this->success('返回成功', $ret);
    }
}
